package com.imc.platform.base.common.service;

import com.imc.platform.base.common.pojo.IdentifyCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.Date;

/**
 * Created by tanweiping on 2018/8/1.
 */
/*
* 类描述：图形验证码的校验服务类
* 开发者：tanweiping
* 创建日期：2018/8/7 10:38
*/
@Transactional
@Service
public class IdentifyCodeService {

    /*
    5分钟
     */
    final long validTime = 300;

//    @Autowired
//    IdentifyCodeRepository identifyCodeRepository;

    /*
    * tanweiping  2018/8/7 10:38
    * 方法描述：生成位置
    */
    public String getIdentifyCode(HttpSession  session, String start_, String end_){
        //Math.round(Math.random() * (end - start) + start)
        int start = Integer.valueOf(start_).intValue();
        int end = Integer.valueOf(end_).intValue();
        long code = Math.round(Math.random() * (end-start)+start);
        String code_ =  String.valueOf(code);
        Date d = new Date();
        IdentifyCode identifyCode =  IdentifyCode
                .builder()
                .effectTime(d)
                .invalidTime(new Date(d.getTime()+validTime))
                .code(code_)
                .build();
        session.setAttribute("identifyCode",identifyCode);
//        identifyCodeRepository.save(
//            IdentifyCode
//                    .builder()
//                    .userName(username)
//                    .effectTime(d)
//                    .invalidTime(new Date(d.getTime()+validTime))
//                    .code(code_)
//                    .build()
//        );
        return code_;
    }

    /*
    * tanweiping  2018/8/7 10:38
    * 方法描述：验证位置
    */
    public boolean verify(HttpSession session,String code){
//        IdentifyCode identifyCode =
//                identifyCodeRepository.findFirstByUserNameAndInvalidTimeLessThanEqualAndValidAndTypeOrderByEffectTimeDesc(
//                username,new Date(),"0","position"
//        );
        IdentifyCode identifyCode = (IdentifyCode)session.getAttribute("identifyCode");
        if (identifyCode!=null){
            //return identifyCode.getCode().endsWith(code);
            //identifyCode.setValid("-1");
            //identifyCodeRepository.save(identifyCode);
            session.removeAttribute("identifyCode");
            return Math.abs(Integer.valueOf(code).intValue() - Integer.valueOf(identifyCode.getCode()).intValue()) < 10;
        }
        return false;
    }
}
